package com.jinyi.wwdeng.autodialer.ui

import android.view.KeyEvent
import android.view.MotionEvent
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.jinyi.wwdeng.autodialer.R
import com.jinyi.wwdeng.autodialer.http.HttpCallback
import com.jinyi.wwdeng.autodialer.http.HttpUtil
import com.jinyi.wwdeng.autodialer.manager.LoadingManager
import org.json.JSONObject

open class BaseAct: AppCompatActivity() {
    private val loadingManager by lazy { LoadingManager.getInstance() }

    /**
     * 显示加载对话框
     */
    protected fun showLoading() {
        showLoading(true)
    }

    /**
     * 显示加载对话框
     */
    protected fun showLoading(cancel: Boolean) {
        loadingManager.show(this, null, cancel)
    }

    /**
     * 隐藏加载对话框
     */
    protected fun hideLoading() {
        loadingManager.dismiss()
    }

    fun showToast(msg: String?){
        msg?.let {
            Toast.makeText(this,msg, Toast.LENGTH_SHORT).show()
        }
    }

    fun post(url: String, body: JSONObject, headers: Map<String, String>? = null,callback: HttpCallback? = null){
        HttpUtil.getInstance().postJson(this,url,body.toString(),null,object : HttpCallback{
            override fun onSuccess(data: JSONObject) {
                when(data.optInt("code")){
                    0 -> {
                        runOnUiThread {
                            callback?.onSuccess(data)
                        }
                    }
                    else -> {
                        runOnUiThread {
                            showToast(data.optString("msg"))
                        }
                    }
                }
            }
            override fun onFailure(error: String) {
                runOnUiThread {
                    callback?.onFailure(error)
                    showToast(error)
                }
            }

            override fun onFinish() {
                runOnUiThread {
                    callback?.onFinish()
                    hideLoading()
                }
            }
        })
    }

    /* 隐藏键盘 */
    fun onHideSoftInput(v: View?) {
        val imm = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(v?.windowToken, 0)
    }

    /* 显示键盘 */
    fun onShowSoftInput(view: View?) {
        view?.let { v ->
            v.requestFocus()
            val imm = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
            v.postDelayed({
                imm.showSoftInput(v,0)
            },100)
        }
    }

    // 点击外部隐藏键盘
    override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
        if (ev.action == MotionEvent.ACTION_DOWN) {
            // 获得当前得到焦点的View，一般情况下就是EditText（特殊情况就是轨迹求或者实体案件会移动焦点）
            val v = currentFocus
            onHideSoftInput(v)
        }
        return super.dispatchTouchEvent(ev)
    }

    private var exitTime: Long = 0
    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.action == KeyEvent.ACTION_DOWN) {
            if (System.currentTimeMillis() - exitTime > 2000) {
                showToast(getString(R.string.tips_exit))
                exitTime = System.currentTimeMillis()
            } else {
//                    System.exit(0);
                finish()
            }
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    override fun onDestroy() {
        super.onDestroy()
        HttpUtil.getInstance().cancelRequests(this)
    }
}